package org.example.springboot3.service.impl;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.example.springboot3.service.JwtUtilsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Service
public class JwtUtilsImpl implements JwtUtilsService {
    //密钥签名
    @Value("${jwt.secret}")
    private String secretKey;
    //过期时间
    @Value("${jwt.expiration}")
    private Long expiration;

    private Key getSigningKey() {
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public String createToken(Map<String, Object> claims) {
        //过期时间
        Date date;
        date = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder()
                .claims(claims)
                .expiration(date)
                .signWith(getSigningKey())
                .compact();
    }

    public boolean verifyToken(String token){
        try {
            parseToken(token);
            return true; // 验证通过
        }catch (ExpiredJwtException e) {
            System.err.println("Token已过期: " + e.getMessage());
        } catch (UnsupportedJwtException e) {
            System.err.println("不支持的JWT格式: " + e.getMessage());
        } catch (MalformedJwtException e) {
            System.err.println("无效的JWT结构: " + e.getMessage());
        }  catch (IllegalArgumentException e) {
            System.err.println("JWT为空或格式错误: " + e.getMessage());
        }
        return false;
    }

    public Jws<Claims> parseToken(String token) {
        // 构建JWT解析器并设置验证规则
        return Jwts.parser()
                .verifyWith((SecretKey) getSigningKey())// 验证签名
                .build()
                .parseSignedClaims(token);// 解析Token
    }
}